<!--
 * @Descripttion: 编辑活动
 * @Author: xiao li
 * @Date: 2020-10-15 10:24:27
 * @LastEditors: xiao li
 * @LastEditTime: 2022-01-20 19:28:39
-->
<template>
  <div>
    <top-nav :title="navTitle" :isBack="true"></top-nav>
    <div class="page-main">
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="subForm"
        label-width="140px"
      >
        <el-form-item label="活动名" prop="title">
          <el-input
            v-model="subForm.title"
            placeholder="请输入活动名"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="cate_id">
          <el-select v-model="subForm.cate_id" placeholder="请选择">
            <el-option
              v-for="item in classifyOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <lb-cover
            :fileList="subForm.cover"
            @selectedFiles="getCover"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 686 * 390</lb-tool-tips>
        </el-form-item>
        <el-form-item label="轮播图片" prop="imgs">
          <lb-cover
            type="more"
            :fileList="subForm.imgs"
            @selectedFiles="selectedFiles($event, 'imgs')"
            @moveFiles="moveFiles($event, 'imgs')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 750</lb-tool-tips>
        </el-form-item>
        <el-form
          @submit.native.prevent
          :model="timeForm"
          :rules="timeFormRules"
          ref="timeForm"
          label-width="140px"
        >
          <el-form-item label="报名时间" prop="signTime">
            <el-date-picker
              :disabled="subForm.id ? true : false"
              v-model="timeForm.signTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="活动时间" prop="activityTime">
            <el-date-picker
              :disabled="subForm.id ? true : false"
              v-model="timeForm.activityTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
        <el-form-item label="报名内容" prop="content">
          <el-select
            v-model="subForm.content"
            multiple
            filterable
            clearable
            collapse-tags
            placeholder="请选择"
          >
            <el-option
              v-for="item in contentOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动门店" prop="store">
          <el-cascader
            :disabled="subForm.id && subForm.user_id ? true : false"
            v-model="subForm.store"
            :options="storeOptions"
            :props="{
              checkStrictly: false,
              multiple: true,
              value: 'id',
              label: 'title'
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="报名人数" prop="num">
          <el-input
            v-model.number="subForm.num"
            :disabled="subForm.id && subForm.user_id ? true : false"
            placeholder="请输入报名人数"
          ></el-input>
          <lb-tool-tips>允许每个门店参与报名的人数</lb-tool-tips>
        </el-form-item>
        <el-form-item label="返现金额" prop="cash">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.cash"
            :disabled="subForm.id ? true : false"
            :controls="false"
            :precision="2"
            :min="0.01"
          ></el-input-number>
          <lb-tool-tips>报名信息审核通过后，报名人员可获得的金额</lb-tool-tips>
        </el-form-item>
        <el-form-item label="详情图片" prop="info_imgs">
          <lb-cover
            type="more"
            :fileList="subForm.info_imgs"
            @selectedFiles="selectedFiles($event, 'info_imgs')"
            @moveFiles="moveFiles($event, 'info_imgs')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * n</lb-tool-tips>
        </el-form-item>
        <el-form-item label="活动介绍" prop="text">
          <lb-ueditor
            v-model="subForm.text"
            :destroy="true"
            v-if="subForm.user_id === 0"
          ></lb-ueditor>
          <el-input
            type="textarea"
            :rows="4"
            v-model="subForm.text"
            placeholder="请输入活动介绍"
            v-else
          ></el-input>
        </el-form-item>
        <el-form-item>
          <lb-button type="primary" @click="submitFormInfo">{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="goBack">{{ $t('action.back') }}</lb-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  reg
} from '@/utils/reg'
export default {
  data () {
    return {
      navTitle: '',
      classifyOptions: [],
      contentOptions: [],
      storeOptions: [],
      subForm: {
        id: 0,
        user_id: 0,
        title: '',
        cate_id: '',
        cover: [],
        imgs: [],
        atv_start_time: '',
        atv_end_time: '',
        signup_start_time: '',
        signup_end_time: '',
        content: [],
        store: [],
        num: '',
        cash: 0.01,
        info_imgs: [],
        text: ''
      },
      subFormRules: {
        title: { required: true, type: 'string', message: '请输入活动名', trigger: 'blur' },
        store: { required: true, type: 'array', message: '请选择门店', trigger: 'blur' },
        cate_id: { required: true, type: 'number', message: '请选择分类', trigger: 'change' },
        cover: { required: true, type: 'array', message: '请上传图片', trigger: 'change' },
        num: { required: true, type: 'number', validator: reg.isNum, trigger: 'blur' },
        cash: { required: true, type: 'number', message: '请输入返现金额', trigger: 'blur' },
        imgs: { required: true, type: 'array', message: '请上传图片', trigger: 'change' },
        content: { required: true, type: 'array', message: '请选择报名内容', trigger: 'change' },
        text: { required: true, type: 'string', message: '请输入活动介绍', trigger: 'blur' }
      },
      timeForm: {
        signTime: '', // 报名时间
        activityTime: '' // 活动时间
      },
      timeFormRules: {
        signTime: { required: true, type: 'array', message: '请选择时间', trigger: 'change' },
        activityTime: { required: true, type: 'array', message: '请选择时间', trigger: 'change' }
      },
      showStore: false,
      tableData: [],
      total: 0,
      multipleSelection: [],
      searchForm: {
        page: 1,
        limit: 100000000,
        title: ''
      }
    }
  },
  created () {
    let { id } = this.$route.query
    this.navTitle = this.$t(id ? 'menu.EditActivity' : 'menu.AddActivity')
    if (id) {
      this.subForm.id = id
      this.getFormInfo(id)
    }
    this.getBaseInfo()
  },
  methods: {
    async getBaseInfo () {
      let [{ code: cateCode, data: cateData }, { code: contentCode, data: contentData }, { code: storeCode, data: storeData }] = await Promise.all([this.$api.overlordCateSelect(), this.$api.overlordContentSelect(), this.$api.overlordAtvStoreSelect()])
      if (cateCode === 200) {
        this.classifyOptions = cateData
      }
      if (contentCode === 200) {
        this.contentOptions = contentData
      }
      if (storeCode === 200) {
        this.storeOptions = [{
          id: 0,
          title: '直营店',
          children: storeData[0]
        }, {
          id: 1,
          title: '加盟店',
          children: storeData[1]
        }]
      }
    },
    handleSelectionChange (val) {
      let arr = []
      val.map((item) => {
        arr.push(item.id)
      })
      this.tableData.map((bitem, bindex) => {
        this.tableData[bindex].check = false
        if (arr.includes(bitem.id)) {
          this.tableData[bindex].check = true
        }
      })
    },
    submitStoreForm () {
      let data = []
      this.tableData.map((item) => {
        if (item.check) {
          data.push(item)
        }
      })
      this.multipleSelection = data
      this.closeStoreForm()
    },
    async getFormInfo (id) {
      let { code, data } = await this.$api.overlordAtvInfo({ id })
      if (code !== 200) return
      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
      this.subForm.cover = [{ url: data.cover }]
      this.subForm.imgs = data.imgs.map(item => {
        return { url: item }
      })
      this.subForm.info_imgs = data.info_imgs && data.info_imgs.length > 0 ? data.info_imgs.map(item => {
        return { url: item }
      }) : []
      this.timeForm.activityTime = [this.handleMomentTime(data.atv_start_time), this.handleMomentTime(data.atv_end_time)]
      this.timeForm.signTime = [this.handleMomentTime(data.signup_start_time), this.handleMomentTime(data.signup_end_time)]
      this.subForm.store = data.store.map(item => {
        return [item.store_type, item.id]
      })

      console.log('this.subForm.store', this.subForm.store)
    },
    submitFormInfo () {
      console.log('11', this.timeForm.activityTime)

      let flag = true
      let formArr = ['subForm', 'timeForm']
      for (let i = 0, len = formArr.length; i < len; i++) {
        this.$refs[formArr[i]].validate(valid => {
          if (!valid) {
            flag = false
            return false
          }
        })
      }
      if (flag) {
        let { timeForm } = this
        let subForm = JSON.parse(JSON.stringify(this.subForm))
        subForm.cover = subForm.cover[0] ? subForm.cover[0].url : ''
        subForm.imgs = subForm.imgs.map(item => { return item.url })
        subForm.info_imgs = subForm.info_imgs.length > 0 ? subForm.info_imgs.map(item => { return item.url }) : []
        subForm.atv_start_time = this.handleTimes(timeForm.activityTime[0])
        subForm.atv_end_time = this.handleTimes(timeForm.activityTime[1])
        subForm.signup_start_time = this.handleTimes(timeForm.signTime[0])
        subForm.signup_end_time = this.handleTimes(timeForm.signTime[1])
        subForm.store = subForm.store.map(item => { return item[1] })
        let urlType = subForm.id ? 'overlordAtvUpdate' : 'overlordAtvAdd'
        this.$api[urlType](subForm).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t('tips.successSub'))
            this.goBack()
          }
        })
      }
    },
    goBack () {
      this.$router.back(-1)
    },
    getCover (img) {
      this.subForm.cover = img
    },
    selectedFiles (imgs, key) {
      this.subForm[key].push(...imgs)
    },
    moveFiles (imgs, key) {
      this.subForm[key] = imgs
    },
    handleMomentTime (time) {
      return new Date(time * 1000)
    },
    handleTimes (time) {
      return parseInt(new Date(time).getTime() / 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.page-main {
  .el-input,
  .el-input-number,
  .el-select,
  .el-cascader {
    width: 300px;
  }
  .el-textarea {
    width: 600px;
  }
}
</style>
